//
//  FindCollectionViewCell.m
//  BLDMusics
//
//  Created by lxd on 16/3/17.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "FindCollectionViewCell.h"
#import "SectionModel.h"
#import "RunLoopPlayScrollView.h"
#import "DSYCarouselModel.h"
#import "DSYSubTableViewCell.h"
#import "DSYCollectTableViewCell.h"
#import "NumberTableViewCell.h"
#import "DSYMessageHUD.h"

#define SECTIONHEIGHT 40
#define HOLDER [UIImage imageNamed:@"recommend_header_placeholder.jpg"]

@interface FindCollectionViewCell ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *findTableView;

@property (nonatomic, retain) NSMutableArray *sourceList;

@property (nonatomic, retain) RunLoopPlayScrollView *crollView;

/**判断更多的分区*/
@property (nonatomic, assign) NSInteger section;

@end

@implementation FindCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self creatSubviews];
        [self dataHandle];
    }
    return self;
}

- (void)dataHandle {
    static NSString *url = @"http://api.dongting.com/frontpage/frontpage?location=0&version=1458197345518&app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone7%2C2&f=f320&s=s310&imsi=&hid=&splus=9.2.1&active=1&net=2&openudid=921fb117b843753583dbf257222bb96a79d3c64e&idfa=5B1500CB-A041-4C95-951A-F6408B90A0BF&utdid=Vule3TyuSLwDAKd%2FfPxZrXTy&alf=201200&bundle_id=com.ttpod.music&latitude=38.88269196885403&longtitude=121.539207307381";
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_findTableView animated:YES];
    hud.labelText = @"努力加载...";
    [APPTools GETWithURL:url par:nil success:^(id responseObject) {
        [_sourceList removeAllObjects];   // 删除所有的数据
        self.sourceList = [SectionModel modelHandleWithArray:responseObject[@"data"]];
        
        // 为了创建轮播
        SectionModel *model = _sourceList[0];
        [self creatHeaderScrollViewWithSource:model.dataList];
        
        
        [hud hide:YES];
        [_findTableView reloadData];
    } filed:^(NSError *error) {
        [hud hide:YES];
        [DSYMessageHUD showAddToView:_findTableView withMessage:@"网络繁忙" animated:YES];
    }];
    
}

- (void)creatSubviews {
    
    self.findTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height) style:UITableViewStylePlain];
    [self.contentView addSubview:_findTableView];
    _findTableView.delegate = self;
    _findTableView.dataSource = self;
    [_findTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableViewCell"];
    [_findTableView registerClass:[DSYSubTableViewCell class] forCellReuseIdentifier:@"subtitleCell"];
    [_findTableView registerClass:[DSYCollectTableViewCell class] forCellReuseIdentifier:@"collectTableViewCell"];
    [_findTableView registerClass:[NumberTableViewCell class] forCellReuseIdentifier:@"numberTableViewCell"];
    _findTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    
    _findTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        [self dataHandle];
        [_findTableView.mj_header endRefreshing];
    }];
}

#pragma mark - tableView的dataSource和delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel *model = _sourceList[indexPath.section + 1];
     // 如果在cell中是collectionView的时候
    if (indexPath.section == 0 || indexPath.section == 2 || indexPath.section == 3 || indexPath.section == 5 || indexPath.section == 6) {
        DSYCollectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectTableViewCell"];
        cell.sourceList = model.dataList;
        
        return cell;
    }
    // 有标题的的cell
    if (indexPath.section == 4 || indexPath.section == 7 || indexPath.section == 8) {
        DSYSubTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"subtitleCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.sourceModel = model.dataList[indexPath.row];
        return cell;
    }
    
    if (indexPath.section == 1) {
        DSYCarouselModel *dsyModel = [model.dataList firstObject];
        NumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"numberTableViewCell"];
        cell.sourceModel = dsyModel.songs[indexPath.row];
        cell.num = indexPath.row + 1;
        
        return cell;
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel *model = _sourceList[indexPath.section + 1];
    DSYCarouselModel *dsyModel = [model.dataList firstObject];
    if (indexPath.section == 1) {
        [DSYDataManager shareDataManager].allDataArray = dsyModel.songs;
        
        
        DSYMusicViewController *musicVC = [DSYMusicViewController sharedMusicPlayingVC];
        
        musicVC.index = indexPath.row;
        
        
        DSYNAVViewController *nav = [DSYNAVViewController shareNavWithRootViewController:musicVC];
        
        
        [[self getViewController] presentViewController:nav animated:YES completion:nil];
    }
    
    // 我是歌手
    if (indexPath.section == 4) {
        DSYCarouselModel *dsyModel1 = model.dataList[indexPath.row];
        WEBViewController *vc = [[WEBViewController alloc] init];
        vc.url = dsyModel1.action_value;
        [[self getNavController] pushViewController:vc animated:YES];
    }
    // 独家专区
    if (indexPath.section == 7) {
        DSYCarouselModel *dsyModel1 = model.dataList[indexPath.row];
        LXDTypeViewController *vc = [[LXDTypeViewController alloc] init];
        vc.ID = dsyModel1.action_value;
        vc.pic = dsyModel1.picUrl;
        vc.type = @"13";
        [[self getNavController] pushViewController:vc animated:YES];
    }
    // 亚洲新歌榜
    if (indexPath.section == 8) {
        DSYCarouselModel *dsyModel1 = model.dataList[indexPath.row];
        WEBViewController *vc = [[WEBViewController alloc] init];
        vc.url = dsyModel1.action_value;
        [[self getNavController] pushViewController:vc animated:YES];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 获取当前的model
    SectionModel *model = _sourceList[section + 1];
    // 如果在cell中是collectionView的时候就返回一个row
    if (section == 0 || section == 2 || section == 3 || section == 5 || section == 6) {
        return 1;
    }
    if (section == 1) {  // 当区为1的时候返回的是songs的个数
        if (model.dataList.count > 0) {
            DSYCarouselModel *dsyModel = model.dataList[0];
            return dsyModel.songs.count;
        }
    }
    return model.dataList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_sourceList.count >= 1) {
        return _sourceList.count - 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel *model = _sourceList[indexPath.section + 1];
    if (indexPath.section == 0) {
        return 70;
    }
    if (indexPath.section == 4 || indexPath.section == 7 || indexPath.section == 8) {
        return SCREEN_WIDTH / 4;
    }
    
    if (indexPath.section == 2 || indexPath.section == 3 || indexPath.section == 5 || indexPath.section == 6) {
        // 返回的是3整数
        NSInteger count = 0;
        if (model.dataList.count % 3 == 0) {
            count = model.dataList.count / 3;
        } else {
            count = model.dataList.count / 3 + 1;
        }
        return count * ((SCREEN_WIDTH - 40) / 3 + 46) + 10;
    }
    if (indexPath.section == 1) {
        return 60;
    }
    
    return 200;
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 获取当前的model
    SectionModel *model = _sourceList[section + 1];

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, SECTIONHEIGHT)];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, model.nameWidth, SECTIONHEIGHT)];
    nameLabel.text = model.name;
    [headerView addSubview:nameLabel];
    
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    moreButton.tag = 1000 +section;
    
    moreButton.frame = CGRectMake(self.contentView.frame.size.width - 60, 0, 50, SECTIONHEIGHT);
    [moreButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [moreButton setTitle:@"更多>" forState:UIControlStateNormal];
    moreButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    if ([model.action_type integerValue] == 0) {
        moreButton.hidden = YES;
    } else {
        moreButton.hidden = NO;
    }
    
    [moreButton addTarget:self action:@selector(moreButtonAction: ) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:moreButton];
    
    UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(nameLabel.frame) + 5, 0, CGRectGetMinX(moreButton.frame) - CGRectGetMaxX(nameLabel.frame) - 20, SECTIONHEIGHT)];
    descLabel.font = [UIFont systemFontOfSize:15.0f];
    descLabel.textColor = [UIColor lightGrayColor];
    if (model.desc.length > 0) {
        descLabel.text = model.desc;
    } else {
        descLabel.text = @"";
    }
    [headerView addSubview:descLabel];
    
    return headerView;
}

- (void)moreButtonAction:(UIButton *)button {
    NSLog(@"%ld", button.tag);
    // 热门歌单
    if (button.tag == 1002) {
        UINavigationController *nav = [self getNavController];
        LXDSongViewController *vc = [[LXDSongViewController alloc] init];
        [nav pushViewController:vc animated:YES];
    }
    // 我是歌手
    if (button.tag == 1004) {
        LXDIsSingerViewController *vc = [[LXDIsSingerViewController alloc] init];
        [[self getNavController] pushViewController:vc animated:YES];
    }
    // 新歌新碟
    if (button.tag == 1005) {
        LXDNewSongViewController *vc = [[LXDNewSongViewController alloc] init];
        [[self getNavController] pushViewController:vc animated:YES];
    }
    
}


- (nullable UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section
{
    // 获取当前的model
    SectionModel *model = _sourceList[section];
    
    UITableViewHeaderFooterView *headerView = [_findTableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, model.nameWidth, 40)];
    nameLabel.text = model.name;
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return SECTIONHEIGHT;
}




#pragma mark - 头视图的创建
- (void)creatHeaderScrollViewWithSource:(NSArray *)source {
    
    // 把参数传递过来的数组处理成最前面后最后面增加元素，用于轮播
    NSMutableArray *arr = [NSMutableArray arrayWithArray:source];
    // 将最后一个元素添加到数组的头部
    [arr insertObject:source[source.count - 1] atIndex:0];
    // 将第一个元素再次添加到数组的尾部
    [arr addObject:arr[1]];
    
    
    self.crollView = [[RunLoopPlayScrollView alloc] initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_WIDTH / 2) playSource:arr];
    // 设置轮播的时间元
    [_crollView setTimerWithTimeInterval:5.0];
    // 设置scrollView的相关属性
    _crollView.scrollView.bounces = NO;
    _crollView.scrollView.showsHorizontalScrollIndicator = NO;
    _crollView.scrollView.showsVerticalScrollIndicator = NO;
    // 指定tableView的视图
    _findTableView.tableHeaderView = _crollView;
    // 开始轮播
    [_crollView startPlay];
    
}

// 获取当前navigation
- (UIViewController*)getViewController {
    
    for (UIView* next = [self superview];next; next = next.superview) {
        
        UIResponder* nextResponder = [next nextResponder];
        
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            
            return (UIViewController *)nextResponder;
            
        }
        
    }
    return nil;
}


// 获取当前navigation
- (UINavigationController*)getNavController {
    
    for (UIView* next = [self superview];next; next = next.superview) {
        
        UIResponder* nextResponder = [next nextResponder];
        
        if ([nextResponder isKindOfClass:[UINavigationController class]]) {
            
            return (UINavigationController *)nextResponder;
            
        }
        
    }
    return nil;
}


@end
